<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Block_Post_Filter_Rating extends Block_Post_Filter_Abstract {

	protected $_from;
	
	protected $_to;
	
	protected $_max;
	
	protected $_min;
	
	protected $_step = 1;
	
	protected $_itemsInited = false;
	
	public function __construct() {
		$this->_requestVar = 'rating';
		$this->setTemplate('post/filter/rating');
	}
	
	protected function _initItems() {
		if ($this->_itemsInited) return;
		$this->_from = $this->_min = 1;
		$this->_to = $this->_max = 5;
		if (App::get($this->getRequestVar()))
			list($this->_from, $this->_to) = $this->stringToValues(App::get($this->_requestVar));
		$this->_itemsInited = true;
	}
	
	public function apply() {
		if ($this->getFrom()!=$this->getMin() || $this->getTo()!=$this->getMax()) {
			$this->_appliedValues = array($this->getFrom(), $this->getTo());
			
			// append filter to collection
			$select = $this->getLayer()->getCollection()->getSelect();
			$cond = sprintf('post.rating >= %s AND post.rating <= %s', $this->getFrom(), $this->getTo());
			$select->where($cond);
		}
	}
	
	public function getMax() {
		$this->_initItems();
		return $this->_max;
	}
	
	public function getMin() {
		$this->_initItems();
		return $this->_min;
	}
	
	public function getFrom() {
		$this->_initItems();
		return $this->_from;
	}
	
	public function getTo() {
		$this->_initItems();
		return $this->_to;
	}
	
	public function getStep() {
		return $this->_step;
	}

	public function getItemUrl() {
		$query = App::get();
		$query[$this->getRequestVar()] = '#from-#to';
		return App::url('*/*', array('_query' => $query));
	}
	
	public function stringToValues($s) {
		return explode('-', $s);
	}
	
}